import request from "@/utils/request";

function jsonToUrlParams(obj) {
  return Object.keys(obj)
    .map((key) => {
      // 处理值为数组的情况（如：key=value1&key=value2）
      if (Array.isArray(obj[key])) {
        return obj[key]
          .map(
            (item) => `${encodeURIComponent(key)}=${encodeURIComponent(item)}`
          )
          .join("&");
      }
      // 处理普通值
      return `${encodeURIComponent(key)}=${encodeURIComponent(obj[key])}`;
    })
    .join("&");
}

const loginApi = {
  // 游客登录
  anonymousLogin: async (params) => {
    const queryString = jsonToUrlParams(params);
    return await request({
      url: `/app/Login/anonymousLogin?${queryString}`,
      method: "POST",
    });
  },
  // 手机号、验证码登录
  phoneLogin: async (params) => {
    const queryString = jsonToUrlParams(params);
    return await request({
      url: `/app/Login/registerCode?${queryString}`,
      method: "POST",
    });
  },
  // 账号密码、登录
  accountLogin: async (params) => {
    const queryString = jsonToUrlParams(params);
    return await request({
      url: `/app/Login/registerCode?${queryString}`,
      method: "POST",
    });
  },
  // 发送验证码 state默认传login
  sendMsg: async (phone) => {
    return await request({
      url: `/app/Login/sendMsg/${phone}`,
      method: "GET",
    });
  },
  // 判断手机号是否已绑定
  phoneIsUse: async (params) => {
    return await request({
      url: `/app/user/existPhone`,
      method: "GET",
      params: params,
    });
  },
  // 绑定手机号
  bindPhone: async (params) => {
    return await request({
      url: `/app/user/updatePhone`,
      method: "POST",
      params: params,
    });
  },
  // 设置密码
  savePwd: async (params) => {
    return await request({
      url: `/app/user/updatePwdByMsg`,
      method: "POST",
      params: params,
    });
  },
};

export default loginApi;
